package webExperiment;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;

//-----------------------------------------------------
public class MultipleChoice extends JPanel implements ActionListener {
    /**
     * new version with show labels in between new action Interface
     */

    private static final long serialVersionUID = 1L;
    private int NoChoices;
    private int selectedItem;
    private ButtonGroup group = new ButtonGroup();
    private JRadioButton[] RB;
    private JLabel[] RB_txt;
    private boolean showLabels;
    private MultipleChoiceActionInterface AI;

    public MultipleChoice(int theNoChoices, Color bgColor) {
	this(theNoChoices, bgColor, 0, 0);
    }

    public MultipleChoice(int theNoChoices, Color bgColor, int hGap,
	    int LabelWidth) {
	if (LabelWidth > 0)
	    showLabels = true;
	else
	    showLabels = false;

	NoChoices = theNoChoices;
	RB = new JRadioButton[NoChoices + 1];
	if (showLabels)
	    RB_txt = new JLabel[NoChoices + 1];
	setBackground(bgColor);
	setLayout(new FlowLayout(FlowLayout.CENTER, hGap, 1));
	// this.setBorder(BorderFactory.createLineBorder(Color.lightGray));
	// setPreferredSize(new Dimension(200,30));
	for (int x = 1; x <= NoChoices; x++) {
	    RB[x] = new JRadioButton();
	    RB[x].setBackground(this.getBackground());
	    RB[x].setActionCommand("" + x);
	    RB[x].addActionListener(this);
	    this.add(RB[x]);
	    if (showLabels) {
		RB_txt[x] = new JLabel();
		RB_txt[x].setPreferredSize(new Dimension(LabelWidth, 20));
		RB_txt[x].setHorizontalAlignment(SwingConstants.LEFT);
		this.add(RB_txt[x]);
	    }
	}
	reset(0); // preSelected
    } // constructor

    public void reset(int preSelected) {
	int x;
	selectedItem = 0;
	// remove group and set to zero
	for (x = 1; x <= NoChoices; x++) {
	    group.remove(RB[x]);
	    RB[x].setSelected(false);
	}
	// make new group
	for (x = 1; x <= NoChoices; x++) {
	    if (preSelected == x) {
		RB[x].setSelected(true);
		selectedItem = x;
	    }
	    ;
	    group.add(RB[x]);
	}
    }

    public boolean setLabel(int idx, String text) {
	if (showLabels && (idx <= NoChoices)) {
	    RB_txt[idx].setText(text);
	    return true;
	}
	return false;
    }

    public int getSelectedItem() {
	return selectedItem;
    }

    public void addMultipleChoiceActionInterface(
	    MultipleChoiceActionInterface actionInterface) {
	AI = actionInterface;
    }

    public void actionPerformed(ActionEvent e) {
	selectedItem = Integer.parseInt(e.getActionCommand());
	if (AI != null) {
	    AI.clickMultipleChoiceAlternative();
	}
    }
} // MultiChoice

